from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from struct import pack
from cryptography.hazmat.backends import default_backend


def create_decipher(pos, parsed_file):
    parsed_file['iv'][12:16] = pack('>I', pos)
    if parsed_file["encoding"].lower() == 'aes-256-cbc':
        cipher = Cipher(algorithms.AES(parsed_file['enc_key']), modes.CBC(bytes(parsed_file['iv'])))
    else:
        raise ValueError('Unsupported encoding')
    return cipher.decryptor()


def decrypt_dek(dek_hex, kek):
    decryptor = Cipher(algorithms.AES(kek), modes.CBC(bytes(16)), backend=default_backend()).decryptor()
    return decryptor.update(bytes.fromhex(dek_hex)) + decryptor.finalize()
